{% extends 'base/base.html' %}
{% load static %}

{% block title %}智能客服 - 盲盒商城{% endblock %}

{% block extra_css %}
<style>
    .chat-container {
        height: 70vh;
        background-color: #f9f9f9;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        overflow-y: auto;
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    
    .message {
        margin-bottom: 15px;
        display: flex;
    }
    
    .message-content {
        max-width: 70%;
        padding: 10px 15px;
        border-radius: 18px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        white-space: pre-line;
    }
    
    .user-message {
        justify-content: flex-end;
    }
    
    .user-message .message-content {
        background-color: #0D6EFD;
        color: white;
        border-bottom-right-radius: 5px;
    }
    
    .assistant-message {
        justify-content: flex-start;
    }
    
    .assistant-message .message-content {
        background-color: white;
        color: #333;
        border-bottom-left-radius: 5px;
    }
    
    .message-input {
        display: flex;
        margin-top: 20px;
    }
    
    .message-input input {
        flex-grow: 1;
        padding: 12px 15px;
        border: 1px solid #ddd;
        border-radius: 25px;
        font-size: 16px;
    }
    
    .message-input button {
        margin-left: 10px;
        padding: 12px 25px;
        border: none;
        border-radius: 25px;
        background-color: #0D6EFD;
        color: white;
        font-size: 16px;
        cursor: pointer;
        transition: background-color 0.3s;
    }
    
    .message-input button:hover {
        background-color: #0b5ed7;
    }
    
    .typing-indicator {
        display: none;
        margin-bottom: 15px;
    }
    
    .typing-indicator .message-content {
        background-color: white;
        color: #333;
        border-bottom-left-radius: 5px;
        padding: 10px 15px;
    }
    
    .dot {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: #bbb;
        margin-right: 3px;
        animation: pulse 1.5s infinite;
    }
    
    .dot:nth-child(2) {
        animation-delay: 0.2s;
    }
    
    .dot:nth-child(3) {
        animation-delay: 0.4s;
    }
    
    @keyframes pulse {
        0% { transform: scale(1); opacity: 1; }
        50% { transform: scale(1.3); opacity: 0.7; }
        100% { transform: scale(1); opacity: 1; }
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-5 mb-5">
    <div class="row">
        <div class="col-md-12">
            <h2 class="mb-4">智能客服</h2>
            
            <div class="chat-container" id="chat-container">
                {% if messages %}
                    {% for message in messages %}
                        <div class="message {% if message.role == 'user' %}user-message{% else %}assistant-message{% endif %}">
                            <div class="message-content">
                                {{ message.content|linebreaksbr }}
                            </div>
                        </div>
                    {% endfor %}
                {% else %}
                    <div class="message assistant-message">
                        <div class="message-content">
                            您好！我是盲盒商城的智能客服，请问有什么可以帮助您的？
                        </div>
                    </div>
                {% endif %}
                
                <div class="typing-indicator assistant-message" id="typing-indicator">
                    <div class="message-content">
                        <span class="dot"></span>
                        <span class="dot"></span>
                        <span class="dot"></span>
                    </div>
                </div>
            </div>
            
            <div class="message-input">
                <input type="text" id="message-input" placeholder="请输入您的问题..." class="form-control">
                <button id="send-button" class="btn btn-primary">发送</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 会话ID
    const sessionId = "{{ session_id }}";
    
    // 聊天容器
    const chatContainer = document.getElementById('chat-container');
    
    // 输入框和发送按钮
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    
    // 打字指示器
    const typingIndicator = document.getElementById('typing-indicator');
    
    // 自动滚动到底部
    function scrollToBottom() {
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }
    
    // 页面加载完成后滚动到底部
    window.onload = function() {
        scrollToBottom();
    };
    
    // 添加消息到聊天
    function addMessage(content, isUser) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isUser ? 'user-message' : 'assistant-message'}`;
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        
        // 将内容中的换行符保留
        messageContent.innerHTML = content.replace(/\n/g, '<br>');
        
        messageDiv.appendChild(messageContent);
        
        // 将打字指示器之前插入消息
        chatContainer.insertBefore(messageDiv, typingIndicator);
        scrollToBottom();
    }
    
    // 显示打字指示器
    function showTypingIndicator() {
        typingIndicator.style.display = 'flex';
        scrollToBottom();
    }
    
    // 隐藏打字指示器
    function hideTypingIndicator() {
        typingIndicator.style.display = 'none';
    }
    
    // 发送消息
    async function sendMessage() {
        const message = messageInput.value.trim();
        if (!message) return;
        
        // 清空输入框
        messageInput.value = '';
        
        // 添加用户消息
        addMessage(message, true);
        
        // 显示打字指示器
        showTypingIndicator();
        
        try {
            // 发送API请求
            const response = await fetch('{% url "chatbot:chat_api" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    session_id: sessionId
                })
            });
            
            const data = await response.json();
            
            // 隐藏打字指示器
            hideTypingIndicator();
            
            if (response.ok) {
                // 添加AI回复
                addMessage(data.response, false);
            } else {
                // 添加错误消息
                addMessage('抱歉，服务器出现了问题，请稍后再试。', false);
                console.error('API错误:', data.error);
            }
        } catch (error) {
            // 隐藏打字指示器
            hideTypingIndicator();
            
            // 添加错误消息
            addMessage('抱歉，连接服务器时出现了问题，请检查您的网络连接。', false);
            console.error('请求错误:', error);
        }
    }
    
    // 监听发送按钮点击
    sendButton.addEventListener('click', sendMessage);
    
    // 监听输入框回车键
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            sendMessage();
        }
    });
</script>
{% endblock %} 